package com.huika.dealontop.control.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.hk.app.android.lib.http.AjaxParams;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.dealontop.R;
import com.huika.dealontop.support.http.FlagResultRequest;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.ServerFlagError;
import com.huika.dealontop.support.http.ServerJsonUnParseError;
import com.huika.dealontop.views.LoadingDialog;
import com.huika.dealontop.views.ToastMsg;
import com.huika.dealontop.views.common.CommonLoadingView;
import com.huika.dealontop.views.common.CommonNoNetView;
import com.huika.dealontop.views.overlay.OverlayLayout;
import com.huika.huikalib.base.activity.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;

public abstract class BaseAct extends BaseActivity implements ErrorListener,
        OnCancelListener {
    public static final String LEFT_TITLE = "leftTitle";// 所有左侧显示字符的传递key
    /**
     * 分页加载数据，每页数据量
     */
    public static final int PAGE_SIZE = 10;
    /**
     * 当前页，用于分页加载数据
     */
    public int CURRENT_PAGE = 1;
    protected LayoutInflater inflater;
    protected Context context;
    public LoadingDialog loadingDialog;
    protected View netErrorView;
    private OverlayLayout mEmtyOverlay;
    private View commonEmtyOverlay;

    public BaseAct() {
        setHiddenActionBar(true);
        // setBackListener(false);
        // setScreenOrientation(ScreenOrientation.VERTICAL);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = this;
        inflater = LayoutInflater.from(context);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);
    }

    protected void initLoadingDialog(boolean isTrans) {
        if (null == loadingDialog) {
            loadingDialog = new LoadingDialog(this, isTrans);
            loadingDialog.setOnCancelListener(this);
        }
    }

    public void showLoadingDialog(String parameter) {
        initLoadingDialog(true);//透明
        loadingDialog.setTitle(parameter);
        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (null != loadingDialog) {
            LoadingDialog.dismissDialog(loadingDialog);
        }
    }

    public void showToastMsg(String msg) {
        ToastMsg.showToastMsg(this, msg);
    }

    public void showToastMsg(int strId) {
        ToastMsg.showToastMsg(this, strId);
    }


    /***
     * 事件监听view的id=R.id.click_reload 显示加载异常
     *
     * @param reloadListener
     */
    protected void setNetErrorClick(View.OnClickListener reloadListener) {
        initNetErrorView();
        if (reloadListener != null) {
            netErrorView.findViewById(R.id.click_reload).setOnClickListener(reloadListener);
            netErrorView.findViewById(R.id.click_checknetwork).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 检查网络设置
                    Intent intent = new Intent(Settings.ACTION_SETTINGS);
                    startActivity(intent);
                }
            });
        }
    }

    protected View initNetErrorView() {
        if (netErrorView == null) {
            initOverlayLayout();
            netErrorView = mOverlayLayout
                    .setOverlayView(R.layout.common_load_error);
        }
        return netErrorView;
    }

    protected void initOverlayLayout() {
        if (mOverlayLayout == null)
            mOverlayLayout = new OverlayLayout(this);
    }

    /**
     * 设置overlay依附的viewgroup
     */
    protected void setOverLayAttachTo(View targetView) {
        initOverlayLayout();
        mOverlayLayout.attachTo(targetView);
    }

    private Set<Object> tags = new HashSet<Object>();

    /**
     * 显示数据空页面 : targetView为设置overlay依附的view,resid为提示信息资源id
     */
    public void showEmptyLayView(View targetView, int resid, int rid) {
        if (mEmtyOverlay == null) {
            mEmtyOverlay = new OverlayLayout(this);
            mEmtyOverlay.attachTo(targetView);
            commonEmtyOverlay = inflater.inflate(R.layout.search_empty_view,
                    null);
            TextView empt_tv = (TextView) commonEmtyOverlay
                    .findViewById(R.id.tv_emptycontent);
            ImageView empt_iv = (ImageView) commonEmtyOverlay
                    .findViewById(R.id.search_ImageView);

            if (resid != -1) {
                empt_tv.setText(resid);
            }
            if (rid != -1) {
                empt_iv.setBackgroundResource(rid);
            }

            mEmtyOverlay.setOverlayView(commonEmtyOverlay);
        }
        mEmtyOverlay.showOverlay();
    }

    /**
     * 影藏数据空页面
     */
    public void hideEmptyLayView() {
        if (mEmtyOverlay != null)
            mEmtyOverlay.hideOverlay();
    }

    /**
     * 添加网络请求
     *
     * @param request
     */
    public void executeRequest(FormResultRequest request) {
        AjaxParams ajaxParams = request.getRequestParams();
//        ajaxParams.putCommonTypeParam("lang", getResources().getString(R.string.common_lang));
        ajaxParams.putCommonTypeParam("lang", getString(R.string.common_lang));
        VolleyRequestManager.addRequest(request, this);
        tags.add(this);
    }

    /**
     * 添加网络请求
     *
     * @param request
     */
    public void executeRequest(FlagResultRequest request) {
        AjaxParams ajaxParams = request.getRequestParams();
        ajaxParams.putCommonTypeParam("lang", getString(R.string.common_lang));
        VolleyRequestManager.addRequest(request, this);
        tags.add(this);
    }

    /**
     * 添加网络请求
     *
     * @param request
     */
    protected void executeRequest(Request request, Object tag) {
        VolleyRequestManager.addRequest(request, tag);
        tags.add(tag);
    }

    /**
     * 取消网络请求
     *
     * @param tag
     */
    protected void cancelRequest(Object tag) {
        VolleyRequestManager.cancelAll(tag);
    }

    @Override
    public void onStop() {
        super.onStop();
        for (Object tag : tags) {
            VolleyRequestManager.cancelAll(tag);
        }
    }

    /**
     * 校验输入
     *************************/
    /* 获取输入内容 */
    public String getInputStr(EditText et) {
        return et.getText().toString().trim();
    }


    // 默认网络请求异常回调
    @Override
    public void onErrorResponse(VolleyError error) {
        if (isOvarallLoading) {
            stopOverallLoading();
        } else {
            dismissLoadingDialog();
        }
        if (CURRENT_PAGE > 1) {// 加载异常回退到当前页
            CURRENT_PAGE--;
        }
        String msg = getResources().getString(R.string.error_response);
        if (error instanceof ServerFlagError) {
            msg = ((ServerFlagError) error).result.msg;
        } else if (error instanceof ServerJsonUnParseError) {
            try {
                String res = ((ServerJsonUnParseError) error).result;
                JSONObject jsonObject = new JSONObject(res);
                msg = jsonObject.getString("msg");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            try {
                if (error.networkResponse != null
                        && error.networkResponse.data != null) {
                    msg = new String(error.networkResponse.data, "utf-8");
//                    if (TextUtils.isEmpty(msg)) {
//                        msg = "未知异常";
//                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (!TextUtils.isEmpty(msg)) {
            showToastMsg(msg);
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.activity_right_in,
                R.anim.activity_right_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.activity_right_in,
                R.anim.activity_right_out);
    }

    /**
     * loadingdialog取消监听
     */
    @Override
    public void onCancel(DialogInterface dialog) {
    }

    /**
     * 覆盖页
     ******************************/
    protected OverlayLayout mOverlayLayout;

    protected void showOverLay() {
        if (mOverlayLayout != null) {
            mOverlayLayout.showOverlay();
        }
    }

    protected void hideOverLay() {
        if (mOverlayLayout != null) {
            mOverlayLayout.hideOverlay();
        }
    }

    /** 覆盖页 end ******************************/

    /**
     * @param
     * @return void
     * @throws
     * @Description: TODO:：关闭键盘事件
     * @author: 刘成伟（wwwlllll@126.com）
     * @Title: closeInput
     * @date 2014-4-6 上午11:18:36
     */
    public void closeInput() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && this.getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private CommonLoadingView commonLoadingView;
    private CommonNoNetView commonNoNetView;
    private ViewGroup contentViewGroup;
    protected boolean isOvarallLoading = false;//是否为全局加载

    /**
     * 全局加载
     *
     * @param contentViewGroup
     */
    public void startOverallLoading(ViewGroup contentViewGroup) {
        isOvarallLoading = true;
        initContentView(contentViewGroup);
        if (parentView != null) {
            parentView.removeViewAt(indexOfContent);
            commonLoadingView = (CommonLoadingView) LayoutInflater.from(this).inflate(R.layout.common_load_view, null);
            commonLoadingView.setLayoutParams(contentParas);
            commonLoadingView.startLoading();
            parentView.addView(commonLoadingView, indexOfContent);
        }
    }

    public void stopOverallLoading() {
        isOvarallLoading = false;
        // commonLoadingView.stopLoading();
        if (parentView != null) {
            parentView.removeViewAt(indexOfContent);
            contentViewGroup.setLayoutParams(contentParas);
            parentView.addView(contentViewGroup, indexOfContent);
        }
    }


    public void showNoNetView(ViewGroup contentViewGroup, OnClickListener onClickListener) {
        initContentView(contentViewGroup);
        if (parentView != null) {
            parentView.removeViewAt(indexOfContent);
            commonNoNetView = (CommonNoNetView) LayoutInflater.from(this).inflate(R.layout.common_nonet_view, null);
            commonNoNetView.setLayoutParams(contentParas);
            commonNoNetView.setReload(onClickListener);
            commonNoNetView.setCheckNet(this);
            parentView.addView(commonNoNetView, indexOfContent);
        }
    }

    public void hideNoNetView() {
        if (parentView != null) {
            parentView.removeViewAt(indexOfContent);
            parentView.addView(contentViewGroup, indexOfContent);
        }
    }

    private int indexOfContent;
    private ViewGroup parentView;
    private ViewGroup.LayoutParams contentParas;

    private void initContentView(ViewGroup contentViewGroup) {
        this.contentViewGroup = contentViewGroup;
        contentParas = contentViewGroup.getLayoutParams();
        parentView = (ViewGroup) contentViewGroup.getParent();
        if (parentView != null) {
            indexOfContent = parentView.indexOfChild(contentViewGroup);
        }
    }
}
